<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form onsubmit="return false">
    <textarea name="message" id="messageText" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="发送消息" onclick="sendMessage(this.form.message.value)">
    <textarea id="responseText" style="height: 300px;width: 300px"></textarea>
    <input type="button" value="清空内容"
           onclick="document.getElementById('responseText').value='';
           document.getElementById('messageText').value=''">
</form>
</body>

<script>
    var socket;
    // 首先判断游览器是否支持 WebSocket编程
    if (window.WebSocket) {
        //GOON
        // JavaScript提供建立WebSocket的接口
        socket = new WebSocket("ws://localhost:10001/connect")

        // 当连接建立时
        socket.onopen = function (ev) {
            document.getElementById("responseText").value = "连接开启..."
        }

        // 相当于 Netty 的handler中的ChannelRead0事件，监听服务端回复消息
        socket.onmessage = function (ev) {
            var rt = document.getElementById("responseText")
            rt.value = rt.value + "\n" + ev.data
        }

        // 当连接被关闭时(特服务器端下线)
        socket.onclose = function (ev) {
            var rt = document.getElementById("responseText")
            rt.value = rt.value + "\n" + "连接关闭..."
        }
    } else {
        alert("当前游览器不支持WebSocket")
    }

    // 发送消息给服务端
    function sendMessage(message) {
        // 首先判断socket是否建立成功
        if (!window.socket) {
            return;
        }
        if (socket.readyState === WebSocket.OPEN) {
            socket.send(message)
        } else {
            alert("连接没有开启")
        }
    }

</script>
</html>